// src/user/user.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../entities/User.entity';
import * as bcrypt from 'bcryptjs';
import { JwtService } from '../../auth/jwt.service';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    private jwtService: JwtService,
  ) {
  }

  async register(username: string, password: string): Promise<void> {
    const existingUser = await this.userRepository.findOne({ where: { username } });
    if (existingUser) {
      throw new Error('用户名被占用，请更换其他用户名！');
    }

    const hashedPassword = await bcrypt.hash(password, 10);
    const user = this.userRepository.create({ username, password: hashedPassword });
    await this.userRepository.save(user);
  }

  async login(username: string, password: string): Promise<{ token: string }> {
    const user = await this.userRepository.findOne({ where: { username } });
    if (!user) {
      throw new Error('用户名不存在，登录失败！');
    }

    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (!isPasswordValid) {
      throw new Error('密码错误，请重新输入~');
    }

    const payload = { id: user.id, openID: user.wxID };
    const token = await this.jwtService.sign(payload);
    console.log(token);

    return { token: `Bearer ${token}` };
  }


  async findByOpenId(openId: string): Promise<User | null> {
    return this.userRepository.findOne({
      where: { wxID: openId },
    });
  }


  async create(openId: string): Promise<User> {
    const user = new User();
    user.wxID = openId;
    user.username = '微信用户';
    user.nickname = '微信用户';
    user.password = '123456';
    return await this.userRepository.save(user);
  }
}
